﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace PSAMMatrixCloud.Common
{
    public class commonFunction
    {
        private static Regex RegNumber = new Regex("^[0-9]+$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
        private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$
        private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串，和 [a-zA-Z0-9] 语法一样
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

        public static string EncryptKey = "k2c4b62=9{1?j4]6>8-012m8r(7e9,t7";

        public commonFunction()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }



        #region 生成时间字符串: GetTimeString()

        public static string GetTimeString()
        {
            string strYear;
            string strMonth;
            string strDay;
            string strHour;
            string strMinute;
            string strSecond;
            string strResult;

            strYear = System.DateTime.Now.Year.ToString();
            strMonth = System.DateTime.Now.Month.ToString().PadLeft(2, '0');
            strDay = System.DateTime.Now.Day.ToString().PadLeft(2, '0');
            strHour = System.DateTime.Now.Hour.ToString().PadLeft(2, '0');
            strMinute = System.DateTime.Now.Minute.ToString().PadLeft(2, '0');
            strSecond = System.DateTime.Now.Second.ToString().PadLeft(2, '0');
            strResult = strYear.Trim() + strMonth.Trim() + strDay.Trim() +
                strHour.Trim() + strMinute.Trim() + strSecond.Trim();

            return strResult;
        }

        #endregion 生成时间字符串: GetTimeString()



        #region 获得yyyy-mm-dd hh:ff:ss格式

        public static string GetFormatDateTime(DateTime dt, string strFormat)
        {
            string strYear;
            string strMonth;
            string strDay;
            string strHour;
            string strMinute;
            string strSecond;
            string strResult = "";

            strYear = dt.Year.ToString();
            strMonth = dt.Month.ToString().PadLeft(2, '0');
            strDay = dt.Day.ToString().PadLeft(2, '0');
            strHour = dt.Hour.ToString().PadLeft(2, '0');
            strMinute = dt.Minute.ToString().PadLeft(2, '0');
            strSecond = dt.Second.ToString().PadLeft(2, '0');
            if (strFormat == "yyyymmddhhmmss")
                strResult = strYear.Trim() + "-" + strMonth.Trim() + "-" + strDay.Trim() + " " +
                    strHour.Trim() + ":" + strMinute.Trim() + ":" + strSecond.Trim();
            else
                if (strFormat == "yyyymmdd")
                strResult = strYear.Trim() + "-" + strMonth.Trim() + "-" + strDay.Trim();
            else
                    if (strFormat == "yyyymmdd<br>hhmmss")
                strResult = strYear.Trim() + "-" + strMonth.Trim() + "-" + strDay.Trim() + "<br>" +
                    strHour.Trim() + ":" + strMinute.Trim() + ":" + strSecond.Trim();

            return strResult;
        }

        #endregion 获得yyyy-mm-dd hh:ff:ss格式

        #region 去除字符串中特殊的字符

        public static string InputText(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            // check incoming parameters for null or blank string
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //convert some harmful symbols incase the regular
                //expression validators are changed
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;

                        case '<':
                            retVal.Append("&lt;");
                            break;

                        case '>':
                            retVal.Append("&gt;");
                            break;

                        case '&':
                            retVal.Append("&amp;");
                            break;

                        case '\n':
                            retVal.Append("<br>");
                            break;

                        case '\r':
                            retVal.Append("");
                            break;

                        case ' ':
                            retVal.Append("&nbsp;");
                            break;

                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }

                // Replace single quotes with white space
                retVal.Replace("'", "''");
            }

            return retVal.ToString();
        }

        #endregion 去除字符串中特殊的字符

        #region 转化字符串中特殊的字符

        public static string OutputText(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            // check incoming parameters for null or blank string
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs

                //convert some harmful symbols incase the regular
                //expression validators are changed

                inputString = inputString.Replace("&quot;", "\"");
                inputString = inputString.Replace("&lt;", "<");
                inputString = inputString.Replace("&gt;", ">");

                inputString = inputString.Replace("&amp;", "&");
                inputString = inputString.Replace("<br>", "\n");
                inputString = inputString.Replace("<br>", "\n");
                inputString = inputString.Replace("&nbsp;", " ");

                // Replace single quotes with white space
                inputString = inputString.Replace("'", "''");

                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);
            }

            return inputString.ToString();
        }

        #endregion 转化字符串中特殊的字符

        #region 去除字符串中特殊的字符(不限字符串长度)

        public static string InputText(string inputString)
        {
            StringBuilder retVal = new StringBuilder();

            // check incoming parameters for null or blank string
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs

                //convert some harmful symbols incase the regular
                //expression validators are changed
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;

                        case '<':
                            retVal.Append("&lt;");
                            break;

                        case '>':
                            retVal.Append("&gt;");
                            break;

                        case '&':
                            retVal.Append("&amp;");
                            break;

                        case '\n':
                            retVal.Append("<br>");
                            break;

                        case '\r':
                            retVal.Append("");
                            break;

                        case ' ':
                            retVal.Append("&nbsp;");
                            break;

                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }

                // Replace single quotes with white space
                retVal.Replace("'", "''");
            }

            return retVal.ToString();
        }

        #endregion 去除字符串中特殊的字符(不限字符串长度)

        #region 转化字符串中特殊的字符(不限字符串长度)

        public static string OutputText(string inputString)
        {
            StringBuilder retVal = new StringBuilder();

            // check incoming parameters for null or blank string
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //chop the string incase the client-side max length
                //fields are bypassed to prevent buffer over-runs

                //convert some harmful symbols incase the regular
                //expression validators are changed

                inputString = inputString.Replace("&quot;", "\"");
                inputString = inputString.Replace("&lt;", "<");
                inputString = inputString.Replace("&gt;", ">");

                inputString = inputString.Replace("&amp;", "&");
                inputString = inputString.Replace("<br>", "\n");
                inputString = inputString.Replace("<br>", "\n");
                inputString = inputString.Replace("&nbsp;", " ");

                // Replace single quotes with white space
                inputString = inputString.Replace("'", "''");
            }

            return inputString.ToString();
        }

        #endregion 转化字符串中特殊的字符(不限字符串长度)


        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumber(string inputData)
        {
            Match m = RegNumber.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData);
            return m.Success;
        }

        /// <summary>
        /// 判断是否为空(包括空字符串)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsEmpty(object obj)
        {
            if (obj == null || string.IsNullOrEmpty(obj.ToString()) || obj.ToString().Trim().Length <= 0)
            {
                return true;
            }
            return false;
        }


        #region 中文检测

        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }

        #endregion 中文检测

        /// <summary>
        /// 字符串检测，防止sql注入
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static bool ProcessSqlStr(string Str)
        {
            bool ReturnValue = true;
            try
            {
                if (Str != "")
                {
                    string SqlStr = "select*|select *|and '|and'|or '|or'|insertinto|deletefrom|altertable|update|createtable|createview|dropview|createindex|dropindex|createprocedure|dropprocedure|createtrigger|droptrigger|createschema|dropschema|createdomain|alterdomain|dropdomain|);|select@|declare@|print@|char(|select";
                    string[] anySqlStr = SqlStr.Split('|');
                    foreach (string ss in anySqlStr)
                    {
                        if (Str.IndexOf(ss) >= 0)
                        {
                            ReturnValue = false;
                            break;
                        }
                    }
                }
            }
            catch
            {
                ReturnValue = false;
            }
            return ReturnValue;
        }

        #region 其他

        /// <summary>
        /// 检查字符串最大长度，返回指定长度的串
        /// </summary>
        /// <param name="sqlInput">输入字符串</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>
        public static string SqlText(string sqlInput, int maxLength)
        {
            if (sqlInput != null && sqlInput != string.Empty)
            {
                sqlInput = sqlInput.Trim();
                if (sqlInput.Length > maxLength)//按最大长度截取字符串
                    sqlInput = sqlInput.Substring(0, maxLength);
            }
            return sqlInput;
        }

        /// <summary>
        /// 字符串编码
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static string HtmlEncode(string inputData)
        {
            return System.Web.HttpUtility.HtmlEncode(inputData);
        }




       

        /// <summary>
        /// object 转换成string
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjToStr(object obj)
        {
            if (obj == null || obj.ToString() == "")
            {
                return string.Empty;
            }
            else return obj.ToString();
        }

        #endregion 其他

        /// <summary>
        /// 读文件到byte[]
        /// </summary>
        /// <param name="fileName">硬盘文件路径</param>
        /// <returns></returns>
        public static byte[] ReadFileToByte(string fileName)
        {
            FileStream pFileStream = null;
            byte[] pReadByte = new byte[0];
            try
            {
                using (pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    BinaryReader r = new BinaryReader(pFileStream);
                    r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开
                    pReadByte = r.ReadBytes((int)r.BaseStream.Length);
                    return pReadByte;
                }
            }
            catch
            {
                return pReadByte;
            }
        }

        /// <summary>
        /// 写byte[]到fileName
        /// </summary>
        /// <param name="pReadByte">byte[]</param>
        /// <param name="fileName">保存至硬盘路径</param>
        /// <returns></returns>
        public static bool WriteByteToFile(byte[] pReadByte, string fileName)
        {
            FileStream pFileStream = null;
            try
            {
                using (pFileStream = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    pFileStream.Write(pReadByte, 0, pReadByte.Length);
                }
            }
            catch
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// DES 加密(数据加密标准，速度较快，适用于加密大量数据的场合)
        /// </summary>
        /// <param name="EncryptString">待加密的密文</param>
        /// <param name="EncryptKey">加密的密钥</param>
        /// <returns>returns</returns>
        public static string DESEncrypt(string EncryptString, string EncryptKey)
        {
            if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
            if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
            //if (EncryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            string m_strEncrypt = "";
            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                m_stream.Close();
                m_stream.Dispose();
                m_cstream.Close();
                m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_DESProvider.Clear(); }
            return m_strEncrypt;
        }

        /// <summary>

        /// DES 解密(数据加密标准，速度较快，适用于加密大量数据的场合)
        /// </summary>
        /// <param name="DecryptString">待解密的密文</param>
        /// <param name="DecryptKey">解密的密钥</param>
        /// <returns>returns</returns>
        public static string DESDecrypt(string DecryptString, string DecryptKey)
        {
            if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
            if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
            //if (DecryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            string m_strDecrypt = "";
            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_cstream.Close(); m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_DESProvider.Clear(); }
            return m_strDecrypt;
        }

        public static string Encrypt(string toEncrypt, string strKey32)
        {
            //strKey32 = 12345678901234567890123456789012
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(strKey32);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string Decrypt(string toDecrypt, string strKey32)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(strKey32);
            try
            {
                byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {
                return "解密失败" + ex.Message.ToString();
            }
        }

        #region Md5加密

        public static string GetMD5StrNet(string srcStr, string strEncodeType)
        {
            //strEncodeType = "utf-8";
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(strEncodeType).GetBytes(srcStr));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        public static string GetMD5StrNet(byte[] srcBytes)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(srcBytes);
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        public static string GetFileMD5ByFile(string filepath)
        {
            StringBuilder sb = new StringBuilder();
            using (MD5 md5 = MD5.Create())
            {
                using (FileStream fs = File.OpenRead(filepath))
                {
                    byte[] newB = md5.ComputeHash(fs);
                    foreach (byte item in newB)
                    {
                        sb.Append(item.ToString("x2"));
                    }
                }
            }

            return sb.ToString();
        }

        #endregion Md5加密

        #region SHA 加密

        public static string HmacSHA256(string secretKey, string plain)
        {
            var keyBytes = Encoding.UTF8.GetBytes(secretKey);
            var plainBytes = Encoding.UTF8.GetBytes(plain);

            using (var hmacsha256 = new HMACSHA256(keyBytes))
            {
                var sb = new StringBuilder();
                var hashValue = hmacsha256.ComputeHash(plainBytes);
                foreach (byte x in hashValue)
                {
                    sb.Append(String.Format("{0:x2}", x));
                }
                return sb.ToString();
            }
        }

        #endregion SHA 加密

        #region 生成验证码

        public static string GenSerialNo(int intLength)
        {
            string[] strArray;
            int i;
            string strResult = "";
            //strArray = new strArray[30];
            strArray = new string[30];
            strArray[0] = "0";
            strArray[1] = "1";
            strArray[2] = "2";
            strArray[3] = "3";
            strArray[4] = "4";
            strArray[5] = "5";
            strArray[6] = "6";
            strArray[7] = "7";
            strArray[8] = "8";
            strArray[9] = "9";

            strArray[10] = "A";
            strArray[11] = "B";
            strArray[12] = "C";
            strArray[13] = "D";
            strArray[14] = "E";
            strArray[15] = "F";
            strArray[16] = "G";
            strArray[17] = "H";
            strArray[18] = "J";
            strArray[19] = "K";

            strArray[20] = "L";
            strArray[21] = "M";
            strArray[22] = "N";
            strArray[23] = "P";
            strArray[24] = "Q";
            strArray[25] = "R";
            strArray[26] = "S";
            strArray[27] = "T";
            strArray[28] = "U";
            strArray[29] = "V";

            Random a = new Random();
            for (int j = 0; j < intLength; j++)
            {
                i = a.Next(0, 30);
                strResult = strResult + strArray[i].ToString();
            }
            return strResult;
        }

        #endregion 生成验证码

        #region 生成返回结果字符串数组(4个)

        public static string[] InitResultString()
        {
            string[] strResult = new string[4];
            for (int i = 0; i < strResult.Length; i++)
            {
                strResult[i] = "";
            }
            return strResult;
        }

        #endregion 生成返回结果字符串数组(4个)

        public static string JavaMsg(string msg, string action, string url)
        {
            StringBuilder strJava = new StringBuilder();
            strJava.Append("<script>");
            strJava.Append("alert('" + msg + "');");

            switch (action)
            {
                case "back":
                    strJava.Append("history.go(-1);");
                    break;

                case "close":
                    strJava.Append("window.close();");
                    break;

                case "jump":
                    strJava.Append("location.href='" + url + "';");
                    break;

                case "alert":
                default:
                    break;
            }
            strJava.Append("</script>");
            return strJava.ToString();
        }

        /*

		#region 发送邮件

		/// <summary>
		/// 向用户填写的邮箱中发送账户激活信息
		/// </summary>
		/// <param name="from">发件邮箱地址</param>
		/// <param name="to">目的邮箱地址</param>
		/// <param name="subject">邮件标题</param>
		/// <param name="content">邮件内容</param>
		/// <param name="uid">发件用户名</param>
		/// <param name="pwd">发件密码</param>
		/// <param name="server">邮箱服务器地址</param>
		public void SendMail(string from, string to, string subject, string content)
		{
			string server = System.Configuration.ConfigurationSettings.AppSettings["EmailServer"].ToString().Trim();
			string pwd = System.Configuration.ConfigurationSettings.AppSettings["EmailPwd"].ToString().Trim();
			string uid = System.Configuration.ConfigurationSettings.AppSettings["EmailUid"].ToString().Trim();
			MailMessage objMailMessage;
			MailAttachment objMailAttachment;

			// 创建一个附件对象
			//objMailAttachment = new MailAttachment("d:\\test.txt");//发送邮件的附件
			// 创建邮件消息
			objMailMessage = new MailMessage();
			objMailMessage.BodyFormat = MailFormat.Text;
			objMailMessage.From = from;//源邮件地址
			objMailMessage.To = to;//目的邮件地址
			objMailMessage.Subject = subject;//发送邮件的标题
			objMailMessage.Body = content;//发送邮件的内容
			//基本权限
			objMailMessage.Fields.Add("smtpauthenticate", "1");
			//用户名
			objMailMessage.Fields.Add("sendusername", uid);
			//密码
			objMailMessage.Fields.Add("sendpassword", pwd);
			//如果没有上述三行代码，则出现如下错误提示：服务器拒绝了一个或多个收件人地址。服务器响应为: 554 : Client host rejected: Access denied
			//SMTP地址
			SmtpMail.SmtpServer = server;
			//开始发送邮件
			try
			{
				SmtpMail.Send(objMailMessage);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			//核心代码结束
		}

		#endregion 发送邮件

		*/


        #region 将变量作为属性名称，在model中取值

        public static T GetPropertyFormModel<T>(object obj, string strPropertyName)
        {
            PropertyInfo[] propArray = (obj.GetType()).GetProperties();
            foreach (PropertyInfo prop in propArray)
            {
                if (prop.Name.ToString() == strPropertyName)
                {
                    return (T)prop.GetValue(obj, null);
                }
            }
            return default(T);
        }

        #endregion 将变量作为属性名称，在model中取值

        #region 实体类成员属性转字典

        public static SortedDictionary<string,string> ModelToDictionary<T>(object obj)
        {
            var PropertyDictionary = new SortedDictionary<string, string>();
            if (obj != null)
            {
                PropertyInfo[] propArray = (obj.GetType()).GetProperties();
                foreach (PropertyInfo prop in propArray)
                {
                    PropertyDictionary.Add(prop.Name.ToLower(), prop.GetValue(obj, null).ToString());
                }
            }
            return PropertyDictionary;
        }

        #endregion 将变量作为属性名称，在model中取值

        /// <summary>
        /// 生成随机验证码
        /// </summary>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static string GetCode(int length)
        {
            string str = "abcdefghjklmnpqrstuvwxyz0123456789";

            string code = "";

            Random r = new Random();

            for (int i = 0; i < length; i++)
            {
                int index = r.Next(0, str.Length - 1);
                //随机生成一个位置
                code += str.Substring(index, 1);
            }
            return code;
        }

        /// <summary>
        /// 判断是否属于敏感字符
        /// </summary>
        /// <param name="strRegisterUserName"></param>
        /// <returns></returns>
        public static bool IsInRegisterUserNameBlackList(string strRegisterUserName)
        {
            string blackList = "admin,launch,client,kefu,yuanzheng,administrator";
            blackList = blackList.ToLower();
            string[] arrBlackList = blackList.Split(',');

            for (int i = 0; i < arrBlackList.Length; i++)
            {
                if (strRegisterUserName.ToLower().IndexOf(arrBlackList[i]) > -1)
                {
                    return true;
                }
            }
            return false;
        }

        //过滤HTML标记
        public static string FilterHTML(string strHTMLContent)
        {
            strHTMLContent = System.Text.RegularExpressions.Regex.Replace(strHTMLContent, "<[^>]+>", "", RegexOptions.IgnoreCase);
            strHTMLContent = strHTMLContent.Replace(" ", "");
            strHTMLContent = System.Text.RegularExpressions.Regex.Replace(strHTMLContent, "[&#][a-zA-Z]+;", "", RegexOptions.IgnoreCase);
            return strHTMLContent;
        }

        public static Dictionary<string, int> stringToDictionary(string[] str)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (string var in str)
            {
                dic.Add(var.Substring(0, var.IndexOf('=')), int.Parse(var.Substring(var.IndexOf('=') + 1)));
            }
            return dic;
        }

        public static Dictionary<string, Dictionary<string, int>> stringToDictionary(string str)
        {
            char[] charSeparators = new char[] { '|' };
            string[] strs = str.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (string var in strs)
            {
                dic.Add(var.Substring(0, var.IndexOf(':')), var.Substring(var.IndexOf(':') + 1));
            }
            Dictionary<string, Dictionary<string, int>> fullDic = new Dictionary<string, Dictionary<string, int>>();
            foreach (KeyValuePair<string, string> pair in dic)
            {
                fullDic.Add(pair.Key, stringToDictionary(pair.Value.Split(',')));
            }
            return fullDic;
        }

        /// <summary>
        /// 获取Dictionary key值  无值返回null
        /// </summary>
        /// <param name="dicIn"></param>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetDicKeyValue(Dictionary<string, object> dicIn, string strKey)
        {
            if (dicIn.ContainsKey(strKey))
            {
                if (IsEmpty(dicIn[strKey]))
                {
                    return null;
                }
                return ObjToStr(dicIn[strKey]);
            }
            return null;
        }

        public static string dictionaryToString(Dictionary<string, int> dic)
        {
            string result = "";
            foreach (KeyValuePair<string, int> pair in dic)
            {
                result += setKeyAndValue(pair.Key, pair.Value) + ",";
            }
            return result.LastIndexOf(',') == result.Length - 1 ? result.Substring(0, result.Length - 1) : result;
        }

        public static string dictionaryToString(Dictionary<string, string> dic)
        {
            string result = "";
            foreach (KeyValuePair<string, string> pair in dic)
            {
                result += setCommonPare(pair.Key, pair.Value);
            }
            return result.LastIndexOf('|') == result.Length - 1 ? result.Substring(0, result.Length - 1) : result;
        }

        public static string dictionaryToString(Dictionary<string, Dictionary<string, int>> fullDic)
        {
            string result = "";
            foreach (KeyValuePair<string, Dictionary<string, int>> pair in fullDic)
            {
                string value = dictionaryToString(pair.Value);
                result += setCommonPare(pair.Key, value) + "|";
            }
            return result.LastIndexOf('|') == result.Length - 1 ? result.Substring(0, result.Length - 1) : result;
        }

        public static string setKeyAndValue(string valueKey, int value)
        {
            string result = "";
            result = valueKey + "=" + value.ToString();
            return result;
        }

        public static string setCommonPare(string key, string value)
        {
            string result = "";
            result = key + ":" + value;
            return result;
        }

        /// <summary>
        /// hex码直接转string字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="location"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string GetHexStr(byte[] bytes, int location, int count)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = location; i < location + count; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }

        /// <summary>
        /// 验证固定电话号码
        /// [3位或4位区号；区号可以用小括号括起来；区号可以省略；区号与本地号间可以用减号或空格隔开；可以有3位数的分机号，分机号前要加减号]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsTelePhoneNumber(string input)
        {
            string pattern = @"^(((\(0\d{2}\)|0\d{2})[- ]?)?\d{8}|((\(0\d{3}\)|0\d{3})[- ]?)?\d{7})(-\d{3})?$";
            return IsMatch(input, pattern);
        }

        /// <summary>
        /// 验证手机号码
        /// [可匹配"(+86)013325656352"，括号可以省略，+号可以省略，(+86)可以省略，11位手机号前的0可以省略；11位手机号第二位数可以是3、4、5、8中的任意一个]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsMobilePhoneNumber(string input)
        {
            string pattern = @"^(\((\+)?86\)|((\+)?86)?)0?1[34587]\d{9}$";
            return IsMatch(input, pattern);
        }

        /// <summary>
        /// 验证电话号码（可以是固定电话号码或手机号码）
        /// [固定电话：[3位或4位区号；区号可以用小括号括起来；区号可以省略；区号与本地号间可以用减号或空格隔开；可以有3位数的分机号，分机号前要加减号]]
        /// [手机号码：[可匹配"(+86)013325656352"，括号可以省略，+号可以省略，(+86)可以省略，手机号前的0可以省略；手机号第二位数可以是3、4、5、8中的任意一个]]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsPhoneNumber(string input)
        {
            string pattern = @"^(\((\+)?86\)|((\+)?86)?)0?1[3458]\d{9}$|^(((\(0\d{2}\)|0\d{2})[- ]?)?\d{8}|((\(0\d{3}\)|0\d{3})[- ]?)?\d{7})(-\d{3})?$";
            return IsMatch(input, pattern);
        }

        /// <summary>
        /// 验证邮政编码
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsZipCode(string input)
        {
            //string pattern = @"^\d{6}$";
            //return IsMatch(input, pattern);
            if (input.Length != 6)
                return false;
            int i;
            if (int.TryParse(input, out i))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 验证电子邮箱
        /// [@字符前可以包含字母、数字、下划线和点号；@字符后可以包含字母、数字、下划线和点号；@字符后至少包含一个点号且点号不能是最后一个字符；最后一个点号后只能是字母或数字]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsEmail(string input)
        {
            ////邮箱名以数字或字母开头；邮箱名可由字母、数字、点号、减号、下划线组成；邮箱名（@前的字符）长度为3～18个字符；邮箱名不能以点号、减号或下划线结尾；不能出现连续两个或两个以上的点号、减号。
            //string pattern = @"^[a-zA-Z0-9]((?<!(\.\.|--))[a-zA-Z0-9\._-]){1,16}[a-zA-Z0-9]@([0-9a-zA-Z][0-9a-zA-Z-]{0,62}\.)+([0-9a-zA-Z][0-9a-zA-Z-]{0,62})\.?|((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$";
            string pattern = @"^([\w-\.]+)@([\w-\.]+)(\.[a-zA-Z0-9]+)$";
            return IsMatch(input, pattern);
        }

        /// <summary>
        /// 验证网址（可以匹配IPv4地址但没对IPv4地址进行格式验证；IPv6暂时没做匹配）
        /// [允许省略"://"；可以添加端口号；允许层级；允许传参；域名中至少一个点号且此点号前要有内容]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsURL(string input)
        {
            ////每级域名由字母、数字和减号构成（第一个字母不能是减号），不区分大小写，单个域长度不超过63，完整的域名全长不超过256个字符。在DNS系统中，全名是以一个点“.”来结束的，例如“www.nit.edu.cn.”。没有最后的那个点则表示一个相对地址。
            ////没有例如"http://"的前缀，没有传参的匹配
            //string pattern = @"^([0-9a-zA-Z][0-9a-zA-Z-]{0,62}\.)+([0-9a-zA-Z][0-9a-zA-Z-]{0,62})\.?$";

            //string pattern = @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?$";
            string pattern = @"^([a-zA-Z]+://)?([\w-\.]+)(\.[a-zA-Z0-9]+)(:\d{0,5})?/?([\w-/]*)\.?([a-zA-Z]*)\??(([\w-]*=[\w%]*&?)*)$";
            return IsMatch(input, pattern);
        }

        /// <summary>
        /// 验证字符串是否匹配正则表达式描述的规则
        /// </summary>
        /// <param name="inputStr">待验证的字符串</param>
        /// <param name="patternStr">正则表达式字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsMatch(string inputStr, string patternStr)
        {
            return IsMatch(inputStr, patternStr, false, false);
        }

        /// <summary>
        /// 验证字符串是否匹配正则表达式描述的规则
        /// </summary>
        /// <param name="inputStr">待验证的字符串</param>
        /// <param name="patternStr">正则表达式字符串</param>
        /// <param name="ifIgnoreCase">匹配时是否不区分大小写</param>
        /// <param name="ifValidateWhiteSpace">是否验证空白字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase, bool ifValidateWhiteSpace)
        {
            if (!ifValidateWhiteSpace && commonFunction.IsEmpty(inputStr))
                return false;//如果不要求验证空白字符串而此时传入的待验证字符串为空白字符串，则不匹配
            Regex regex = null;
            if (ifIgnoreCase)
                regex = new Regex(patternStr, RegexOptions.IgnoreCase);//指定不区分大小写的匹配
            else
                regex = new Regex(patternStr);
            return regex.IsMatch(inputStr);
        }

        /// <summary>
        /// 验证IPv4地址
        /// [第一位和最后一位数字不能是0或255；允许用0补位]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsIPv4(string input)
        {
            //string pattern = @"^(25[0-4]|2[0-4]\d]|[01]?\d{2}|[1-9])\.(25[0-5]|2[0-4]\d]|[01]?\d?\d)\.(25[0-5]|2[0-4]\d]|[01]?\d?\d)\.(25[0-4]|2[0-4]\d]|[01]?\d{2}|[1-9])$";
            //return IsMatch(input, pattern);
            string[] IPs = input.Split('.');
            if (IPs.Length != 4)
                return false;
            int n = -1;
            for (int i = 0; i < IPs.Length; i++)
            {
                if (i == 0 || i == 3)
                {
                    if (int.TryParse(IPs[i], out n) && n > 0 && n < 255)
                        continue;
                    else
                        return false;
                }
                else
                {
                    if (int.TryParse(IPs[i], out n) && n >= 0 && n <= 255)
                        continue;
                    else
                        return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 验证IPv6地址
        /// [可用于匹配任何一个合法的IPv6地址]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsIPv6(string input)
        {
            string pattern = @"^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$";
            return IsMatch(input, pattern);
        }

        /// <summary>
        /// 身份证上数字对应的地址
        /// </summary>
        //enum IDAddress
        //{
        //    北京 = 11, 天津 = 12, 河北 = 13, 山西 = 14, 内蒙古 = 15, 辽宁 = 21, 吉林 = 22, 黑龙江 = 23, 上海 = 31, 江苏 = 32, 浙江 = 33,
        //    安徽 = 34, 福建 = 35, 江西 = 36, 山东 = 37, 河南 = 41, 湖北 = 42, 湖南 = 43, 广东 = 44, 广西 = 45, 海南 = 46, 重庆 = 50, 四川 = 51,
        //    贵州 = 52, 云南 = 53, 西藏 = 54, 陕西 = 61, 甘肃 = 62, 青海 = 63, 宁夏 = 64, 新疆 = 65, 台湾 = 71, 香港 = 81, 澳门 = 82, 国外 = 91
        //}

        /// <summary>
        /// 验证一代身份证号（15位数）
        /// [长度为15位的数字；匹配对应省份地址；生日能正确匹配]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsIDCard15(string input)
        {
            //验证是否可以转换为15位整数
            long l = 0;
            if (!long.TryParse(input, out l) || l.ToString().Length != 15)
            {
                return false;
            }
            //验证省份是否匹配
            //1~6位为地区代码，其中1、2位数为各省级政府的代码，3、4位数为地、市级政府的代码，5、6位数为县、区级政府代码。
            string address = "11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91,";
            if (!address.Contains(input.Remove(2) + ","))
            {
                return false;
            }
            //验证生日是否匹配
            string birthdate = input.Substring(6, 6).Insert(4, "/").Insert(2, "/");
            DateTime dt;
            if (!DateTime.TryParse(birthdate, out dt))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 验证二代身份证号（18位数，GB11643-1999标准）
        /// [长度为18位；前17位为数字，最后一位(校验码)可以为大小写x；匹配对应省份地址；生日能正确匹配；校验码能正确匹配]
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsIDCard18(string input)
        {
            //验证是否可以转换为正确的整数
            long l = 0;
            if (!long.TryParse(input.Remove(17), out l) || l.ToString().Length != 17 || !long.TryParse(input.Replace('x', '0').Replace('X', '0'), out l))
            {
                return false;
            }
            //验证省份是否匹配
            //1~6位为地区代码，其中1、2位数为各省级政府的代码，3、4位数为地、市级政府的代码，5、6位数为县、区级政府代码。
            string address = "11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91,";
            if (!address.Contains(input.Remove(2) + ","))
            {
                return false;
            }
            //验证生日是否匹配
            string birthdate = input.Substring(6, 8).Insert(6, "/").Insert(4, "/");
            DateTime dt;
            if (!DateTime.TryParse(birthdate, out dt))
            {
                return false;
            }
            //校验码验证
            //校验码：
            //（1）十七位数字本体码加权求和公式
            //S = Sum(Ai * Wi), i = 0, ... , 16 ，先对前17位数字的权求和
            //Ai:表示第i位置上的身份证号码数字值
            //Wi:表示第i位置上的加权因子
            //Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
            //（2）计算模
            //Y = mod(S, 11)
            //（3）通过模得到对应的校验码
            //Y: 0 1 2 3 4 5 6 7 8 9 10
            //校验码: 1 0 X 9 8 7 6 5 4 3 2
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = input.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != input.Substring(17, 1).ToLower())
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 验证身份证号（不区分一二代身份证号）
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsIDCard(string input)
        {
            if (input.Length == 18)
                return IsIDCard18(input);
            else if (input.Length == 15)
                return IsIDCard15(input);
            else
                return false;
        }

        /// <summary>
        /// 验证经度
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsLongitude(string input)
        {
            ////范围为-180～180，小数位数必须是1到5位
            //string pattern = @"^[-\+]?((1[0-7]\d{1}|0?\d{1,2})\.\d{1,5}|180\.0{1,5})$";
            //return IsMatch(input, pattern);
            float lon;
            if (float.TryParse(input, out lon) && lon >= -180 && lon <= 180)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 验证纬度
        /// </summary>
        /// <param name="input">待验证的字符串</param>
        /// <returns>是否匹配</returns>
        public static bool IsLatitude(string input)
        {
            ////范围为-90～90，小数位数必须是1到5位
            //string pattern = @"^[-\+]?([0-8]?\d{1}\.\d{1,5}|90\.0{1,5})$";
            //return IsMatch(input, pattern);
            float lat;
            if (float.TryParse(input, out lat) && lat >= -90 && lat <= 90)
                return true;
            else
                return false;
        }

        #region 处理传入Model实例中，属性有单引号的情况

        /// <summary>
        /// model强制转换
        /// </summary>
        /// <param name="targetobj">被填充数据的目标对象</param>
        /// <param name="sourceobj">作为参照物的对象</param>
        public static void CopyModel2Model(object targetobj, object sourceobj)
        {
            PropertyInfo[] spropArray = (targetobj.GetType()).GetProperties();
            PropertyInfo[] tpropArray = (sourceobj.GetType()).GetProperties();
            foreach (PropertyInfo sprop in spropArray)
            {
                foreach (PropertyInfo tprop in tpropArray)
                {
                    if (tprop.Name.Trim() == sprop.Name.Trim())
                    {
                        object value1 = tprop.GetValue(sourceobj, null);
                        sprop.SetValue(targetobj, value1, null);
                    }
                }
            }
        }

        private static object GetValueForName(object targetobj, string name)
        {
            PropertyInfo[] tpropArray = (targetobj.GetType()).GetProperties();
            foreach (PropertyInfo prop in tpropArray)
            {
                if (prop.Name.Trim() == name)
                {
                    object value1 = prop.GetValue(targetobj, null);
                    return value1;
                }
            }
            return null;
        }

        #endregion 处理传入Model实例中，属性有单引号的情况

        #region 计算startindex和endindex

        /// <summary>
        /// 计算数据库分页的开始记录位以及结束记录位
        /// </summary>
        /// <param name="PageNo">当前页序</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="RecordCount">总记录数</param>
        /// <param name="startindex">开始位</param>
        /// <param name="endindex">结束位</param>
        public static void CalcStartIndexAndEndIndex(int PageNo, int PageSize, int RecordCount, ref int startindex, ref int endindex)
        {
            int PageCount = (RecordCount / PageSize) + 1;

            if (PageNo <= PageCount)
            {
                startindex = (PageNo - 1) * PageSize + 1;
            }
            else
            {
                startindex = (PageCount - 1) * PageSize + 1;
            }
            endindex = startindex + PageSize - 1;
            if (endindex > RecordCount)//如果endindex大于最大记录数，则....
            {
                endindex = RecordCount;
            }
        }

        #endregion 计算startindex和endindex

        // <summary>
        /// 将Unix时间戳转换为DateTime类型时间
        /// </summary>
        /// <param name="d">double 型数字</param>
        /// <returns>DateTime</returns>
        public static System.DateTime ConvertIntDateTime(double d)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddMilliseconds(d);
            return time;
        }

        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>long</returns>
        public static long ConvertDateTimeInt(System.DateTime time)
        {
            //double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            //intResult = (time- startTime).TotalMilliseconds;
            long t = (time.Ticks - startTime.Ticks) / 10000;            //除10000调整为13位
            return t;
        }

        /// <summary>
        /// 将指定格式时间字符串转换成时间
        /// </summary>
        /// <param name="strDate">时间字符串</param>
        /// <param name="strFormate">格式化</param>
        /// <returns></returns>
        public static DateTime ConvertStrToDateTime(string strDate, string strFormate = "yyyyMMddHHmmss")
        {
            DateTime dateMin = DateTime.MinValue;
            try
            {
                if (IsEmpty(strDate) || IsEmpty(strFormate)) return dateMin;
                return DateTime.ParseExact(strDate, strFormate, System.Globalization.CultureInfo.CurrentCulture);
            }
            catch
            {
                return dateMin;
            }
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static int GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return (int)ts.TotalSeconds;
        }

        /// <summary>
        /// 获取毫秒级时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetTimeMillisecondsStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return (long)ts.TotalMilliseconds;
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        public static long DateTimeToMillisecondsStamp(DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (long)(time - startTime).TotalMilliseconds;
        }

        /// <summary>
        /// 判断时间是否超出
        /// </summary>
        /// <param name="d">传入的时间戳 11位</param>
        /// <param name="times">比较时长 正负时长 单位 秒（s）</param>
        /// <param name="dateCompare">需要比对的时间</param>
        /// <returns></returns>
        public static bool CheckTimeStamp(double d, DateTime dateCompare, double times = 5 * 60)
        {
            DateTime dateIn = ConvertIntDateTime(d);
            if (times < 0) times = -times;
            if ((dateIn.AddSeconds(times) > dateCompare && dateIn <= dateCompare) || (dateIn >= dateCompare && dateIn.AddSeconds(-times) < dateCompare))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 判断时间戳是否错误
        /// </summary>
        /// <param name="strDtae">时间戳字符串</param>
        /// <param name="dateCompare"></param>
        /// <param name="times"></param>
        /// <returns></returns>
        public static bool CheckTimeStamp(string strDtae, DateTime dateCompare, double times = 5 * 60)
        {
            DateTime dateIn = ConvertStrToDateTime(strDtae);
            if (dateIn == DateTime.MinValue) return false;
            if (times < 0) times = -times;
            if ((dateIn.AddSeconds(times) > dateCompare && dateIn <= dateCompare) || (dateIn >= dateCompare && dateIn.AddSeconds(-times) < dateCompare))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 将时间格式化字符串
        /// </summary>
        /// <param name="dateIn"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string ConvertTimeNullableToString(DateTime? dateIn, string format = "yyyy-MM-dd HH:mm:ss")
        {
            if (dateIn == null) return "";
            return dateIn.Value.ToString(format);
        }

        #region 查询AppSettings配置文件中是否存在某个键值对

        public static bool CheckConfigValue(string KeyName)
        {
            if (System.Configuration.ConfigurationManager.AppSettings[KeyName] != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion 查询AppSettings配置文件中是否存在某个键值对

        public static string Config(string key)
        {
            if (CheckConfigValue(key))
            {
                //return System.Configuration.ConfigurationManager.AppSettings[key];
                return System.Configuration.ConfigurationManager.AppSettings[key];
            }

            return "";
        }

        #region 组装简单sql语句

        /// <summary>
        /// 组装简单sql数据
        /// </summary>
        /// <param name="dirCondition"></param>
        /// <returns></returns>
        public static string BuildCondition(Dictionary<string, object> dirCondition)
        {
            string result = "";
            try
            {
                if (dirCondition == null || dirCondition.Count <= 0) return result;
                List<string> tmp = new List<string>();
                foreach (var item in dirCondition)
                {
                    if (!check_name(item.Key)) continue;
                    if (item.Value == null || item.Value.ToString() == "" || item.Value.ToString().Length <= 0) continue;
                    var g = Escape(item.Value.ToString());
                    tmp.Add(string.Format("{0}='{1}'", item.Key, g));
                }

                result = string.Join(" and ", tmp.ToArray());
            }
            catch
            {
                return result;
            }

            return result;
        }

        public static bool check_name(string strName)
        {
            return Regex.IsMatch(strName, "^[a-z0-9A-Z_-]+$");
        }

        public static string Escape(string strInput)
        {
            return Regex.Escape(strInput);
        }

        #endregion 组装简单sql语句

        #region 计算时间差

        public static int TimeDiffSecond(DateTime tEnd, DateTime tStart)
        {
            if (tEnd == null || tStart == null)
            {
                return 0;
            }

            int seconds = (int)new TimeSpan(tEnd.Ticks).Subtract(new TimeSpan(tStart.Ticks)).Duration().TotalSeconds;
            return seconds;
        }

        #endregion 计算时间差

        /// <summary>
        /// 获取字段定义的CuscomFieldAttribute 的msg的值(错误提示用的)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="msgCode"></param>
        /// <returns></returns>
        public static string GetCustomAttrMsg<T>(T obj, string msgCode)
        {
            string errorText = string.Empty;
            try
            {
                foreach (var item in obj.GetType().GetFields())
                {
                    if (Common.commonFunction.ObjToStr(item.GetValue(item.Name)).Trim() != msgCode.Trim())
                    {
                        continue;
                    }
                    var cusAttr = (CustomFieldAttribute[])item.GetCustomAttributes(typeof(CustomFieldAttribute), false);
                    if (cusAttr != null && cusAttr.Length > 0)
                    {
                        errorText = cusAttr[0].Msg;
                    }
                    break;
                }
            }
            catch
            {
                //Common.LogerHelper.exception(msgCode + "不存在" + System.Environment.NewLine + System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
                return errorText;
            }

            return errorText;
        }

        /// <summary>
        /// 获取枚举类型的自定义msg的值
        /// </summary>
        /// <param name="enumName"></param>
        /// <returns></returns>
        public static string GetEnumCustomAttrMsg(Enum enumName)
        {
            string _description = string.Empty;
            FieldInfo _fieldInfo = enumName.GetType().GetField(enumName.ToString());
            CustomFieldAttribute[] _attributes = (CustomFieldAttribute[])_fieldInfo.GetCustomAttributes(typeof(CustomFieldAttribute), false);
            if (_attributes != null && _attributes.Length > 0)
                _description = _attributes[0].Msg;
            else
                _description = enumName.ToString();
            return _description;
        }

        /// <summary>
        /// 经纬度转换成地址
        /// </summary>
        /// <param name="lon"></param>
        /// <param name="lat"></param>
        /// <returns></returns>
        public static string GetPlnaceNameFromLocation(decimal lon, decimal lat)
        {
            try
            {
                if (lon <= 0 || lat <= 0) return "";
                string baiDuApi = "http://api.map.baidu.com/geocoder/v2/?ak=uG9jgPRDfzePHUyanRsGWvms";
                baiDuApi += "&location=" + lat.ToString() + "," + lon.ToString() + "&output=json&pois=0&coordtype=wgs84ll";
                string result = Common.HttpParameterCommon.HttpWebResponseUtility.CreateGetHttpResponse(baiDuApi, 10000, null, null);
                Newtonsoft.Json.Linq.JObject jo = ((Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result));
                string status = jo["status"].ToString();
                if (status == "0")
                {
                    //正常返回23
                    return jo["result"]["formatted_address"].ToString() + jo["result"]["sematic_description"].ToString();
                }
                return "";
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error("commonFunction/GetPlnaceNameFromLocation", ex);
                return "";
            }
        }

        /*
		public static string GetWGSAreaLocationFromBD(string areaLocation)
		{
			string[] locations = areaLocation.Split(',');
			string[] locationWGSs = new string[locations.Length];
			for (int i = 0; i < locations.Length; i++)
			{
				var location = locations[i].Split(' ');
				var wgsGpsModel = GpsOffSet.BDToWGS(double.Parse(location[1]), double.Parse(location[0]));
				locationWGSs[i] = wgsGpsModel.Lon.ToString() + " " + wgsGpsModel.Lat.ToString();
			}
			return string.Join(",", locationWGSs);
		}
        */

        /// <summary>
        /// Convert a List{T} to a DataTable.
        /// </summary>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }

        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }

        /// <summary>
        /// 保留小数位数(四舍五入)
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static decimal Round<T>(T t, int decimals = 2)
        {
            if (t == null || !PSAMMatrixCloud.Common.ClassLibrary.Validator.IsPositiveDoubleAndInter(t.ToString()))
            {
                return 0.00m;
            }

            return decimal.Parse(string.Format("{0:F2}", double.Parse(t.ToString())));
        }

        /// <summary>
        /// 获取datarow里面的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <param name="strColName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T GetDataRowValue<T>(DataRow dr, string strColName, T defaultValue)
        {
            if (!dr.Table.Columns.Contains(strColName))
            {
                return defaultValue;
            }
            try
            {
                return (T)dr[strColName];
            }
            catch
            {
                return defaultValue;
            }
        }
    }
}